package yfdc.douyin.download.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AppCompatDialog
import android.util.Log
import android.webkit.*
import okhttp3.Cookie
import okhttp3.HttpUrl.Companion.toHttpUrl
import yfdc.douyin.download.R
import yfdc.douyin.download.Utils
import java.lang.Exception
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.collections.ArrayList

class CaptchaDialog(context: Context) :
        AppCompatDialog(context, android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar) {
    private var webView: WebView? = null
    private val mMainThreadHandler = Handler()
    private val firstFinish = AtomicBoolean(false);
    @SuppressLint("all")
    public final override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dl_webview)
        setCancelable(false)
        setCanceledOnTouchOutside(false)
        val thiz: CaptchaDialog = this@CaptchaDialog;
        webView = findViewById(R.id.captcha_view)
        webView?.apply {
            settings.javaScriptEnabled = true
            // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
            settings.cacheMode = WebSettings.LOAD_NO_CACHE
            webChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView?, title: String?) {
                    super.onReceivedTitle(view, title)
                    if (title !== null) {
                        if (!title.contains("验证码")) {
                            mMainThreadHandler.post {
                                try {
                                    thiz.dismiss()
                                }catch (ex:Exception){
                                    // ignored
                                }
                            }
                        }
                    }
                }
            }
            // 设置不使用默认浏览器，而直接使用WebView组件加载页面
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    mMainThreadHandler.post {
                        view?.loadUrl(url ?: "")
                    }
                    return true
                }

                override fun onPageFinished(view: WebView?, url: String?) {
                    if ((view ===  null) || (url === null)) return
                    if (firstFinish.get()){
                        return
                    }
                    firstFinish.set(true);
                    Log.d("YFDC", "onPageFinished : $url")
                    val cookie = CookieManager.getInstance().getCookie("https://www.iesdouyin.com/")!!
                    val resolvedCookies = cookie.split(";");
                    val cookies:ArrayList<Cookie> = ArrayList();
                    resolvedCookies.forEach{
                        val cookieIn = it.trim()
                        val sp = cookieIn.indexOf('=');
                        val key = cookieIn.substring(0 until sp)
                        val value = cookieIn.substring(sp + 1);
                        Log.w("Cookie","{key:$key,value:$value}");
                    }
                }
            }
        }
    }

    fun showUrl(url: String) {
        show()
        webView!!.loadUrl(url, mapOf("User-Agent" to Utils.USER_AGENT))
    }

    override fun dismiss() {
        try {
            super.dismiss()
        }catch (ex:Throwable){
            Utils.logException(ex, "BAD")
        }
    }
}
